<?php
/**
 * 功能: 采集管理
 * User: 文丹
 * Date: 2018/7/30 0030
 * Time: 9:58
 */

namespace app\admin\controller;
use app\base\controller\Power;
use think\Db;
import('taobao/TopSdk',EXTEND_PATH);
class Collection extends Power{
    protected $beforeActionList = [
        'first'=> ['only'=>'collector_hold,collector_save,common_collect,type_test,'],

    ];
    protected function first(){
        $result = $this->testing();
    }

    /**
     * 通用采集列表
     */
    public function common(){
        $collectors = Db::name('collector')->where('type',1)->paginate(10);
        $count = Db::name('collector')->where('type',1)->count();

        $this->assign([
            'collectors'=>$collectors,
            'count'=>$count,
            'empty'=>'<tr class="text-c empty"><td colspan="10">暂无数据</td></tr>'
        ]);
        return view('');

    }

    /**
     * 通用采集器添加
     */
    public function collector_add(){
        $id  = intval(input('id'));
        if(!empty($id)){
            $result = Db::name('collector')->where('id',$id)->find();
            $this->assign('result',$result);
        }
        $category = Db::name('goods_type')->where('parent_id',0)->select();
       /* echo "<pre>";
        print_r($category);
        echo "</pre>";*/
        $block    = Db::name('goods_block')->where('is_tao',1)->select();

        $this->assign([
            'category'=>$category,
            'block'=>$block
        ]);
        return $this->fetch('collection:collector_add');
    }

    /**
     * 通用采集器添加保存
     */
    public function collector_hold(){
        $gt_id = intval(input('gt_id'));
        $gb_id = intval(input('gb_id'));
        $name  = trim(input('gt_name'));
        $block  = trim(input('gb_name'));
        $page_size = intval(input('page_size',10));
        $page_no = intval(input('page_no',1));
        $pid = trim(input('pid'));
        $start_tk_rate = trim(input('start_tk_rate'));//佣金下限
        $end_tk_rate = trim(input('end_tk_rate'));//佣金上限
        $has_coupon = trim(input('has_coupon'));//是否有优惠券
        $sort = intval(input('sort'));

        if(empty($gt_id)||empty($gb_id)|| empty($pid)||empty($name)||empty($page_size)||
            empty($page_no)||empty($start_tk_rate)||empty($end_tk_rate)){
            return json(['msg'=>'请填写完整的数据','ok'=>false]);
        }
        $check = Db::name('collector')
            ->where('gt_id',$gt_id)
            ->where('gb_id',$gb_id)
            ->find();
        if($check){
            return json(['msg'=>'该采集器已经存在','ok'=>false]);
        }
        $data = [
            'gt_id'=>$gt_id,
            'gb_id'=>$gb_id,
            'block'=>$block,
            'name'=>$name,
            'page_size'=>$page_size,
            'page_no'=>$page_no,
            'pid'=>$pid,
            'type'=>1,//1通用，2好券清单,3食品（吃货）
            'has_coupon'=>$has_coupon,
            'start_tk_rate'=>$start_tk_rate,
            'end_tk_rate'=>$end_tk_rate,
            'sort'=>$sort,
            'add_time'=>time()
        ];
      /* echo "<pre>";
        print_r($data);
        die;*/
        $result = Db::name('collector')->insert($data);
        if($result){
            return json(['msg'=>'添加成功','ok'=>true]);
        }else{
            return json(['msg'=>'添加失败','ok'=>false]);
        }
    }

    /**
     * 通用采集修改
     */
    public function collector_save(){
        $coll_id = intval(input('coll_id'));
        $gt_id = intval(input('gt_id'));
        $gb_id = intval(input('gb_id'));
        $name  = trim(input('gt_name'));
        $block  = trim(input('gb_name'));
        $page_size = intval(input('page_size',10));
        $page_no = intval(input('page_no',1));
        $pid = trim(input('pid'));
        $start_tk_rate = trim(input('start_tk_rate'));//佣金下限
        $end_tk_rate = trim(input('end_tk_rate'));//佣金上限
        $has_coupon = intval(input('has_coupon'));//是否有优惠券
        $sort = intval(input('sort'));

        if(empty($gt_id)||empty($gb_id)|| empty($pid)||empty($name)||empty($page_size)||
            empty($page_no)||empty($start_tk_rate)||empty($end_tk_rate)){
            return json(['msg'=>'请填写完整的数据','ok'=>false]);
        }
        $check = Db::name('collector')
            ->where('gt_id',$gt_id)
            ->where('gb_id',$gb_id)
            ->whereNotIn('id',$coll_id)
            ->find();
        if($check){
            return json(['msg'=>'该采集器已经存在','ok'=>false]);
        }
        $data = [
            'gt_id'=>$gt_id,
            'gb_id'=>$gb_id,
            'block'=>$block,
            'name'=>$name,
            'page_size'=>$page_size,
            'page_no'=>$page_no,
            'pid'=>$pid,
            'type'=>1,//1通用，2好券清单,3食品（吃货）
            'has_coupon'=>$has_coupon,
            'start_tk_rate'=>$start_tk_rate,
            'end_tk_rate'=>$end_tk_rate,
            'sort'=>$sort
        ];
        /* echo "<pre>";
          print_r($data);
          die;*/
        $result = Db::name('collector')->where('id',$coll_id)->update($data);
        if($result){
            return json(['msg'=>'修改成功','ok'=>true]);
        }else{
            return json(['msg'=>'修改失败','ok'=>false]);
        }
    }

    /**
     * 通用商品采集
     */

    public function common_collect(){
        $id = intval(input('id'));
        if($id<=0){
            return json(['msg'=>'id必须为正整数','ok'=>false]);
        }
        $collector = Db::name('collector')->where('id',$id)->find();
        $lastTime  = $collector['use_time'];//最近一次采集时间

        $last_page  = $collector['last_page'];//最后一次采集页数；
        $last_size  = $collector['last_size'];//最近一次采集数量
        $page_no    = $collector['page_no'];
        $page_size  =  $collector['page_size'];

        if(empty($lastTime)){
            $page            = $page_no;//采集页数
            $number          = $page_size;//采集数量
            $last_page  = $page_no;//最后一次采集页数；
            $last_size  = $page_size;//最近一次采集数量
        }else{
            if($page_no>$last_page && $page_size>$last_size){
                $page            = $page_no;
                $number          = $page_size;
                $last_page  = $page_no;
                $last_size  = $page_size;
            }else{
                $page            = intval($last_page)+intval($page_no);
                $number          = intval($page_size);

                if($last_page>100){
                    $last_page = 100;
                }else{
                    $last_page  = intval($last_page)+intval($page_no);
                    $last_size  = intval($page_size);
                }
            }

        }

        $arr =  [
            'use_time'=>time(),
            'last_page'=>$last_page,
            'last_size'=>$last_size
        ];

        $coll_sort = $collector['sort'];
        $sort = '';
        if($coll_sort==1){
            $sort = 'total_sales_des';
        }elseif($coll_sort==2){
            $sort = 'tk_rate_des';
        }elseif($coll_sort==3){
            $sort = 'tk_total_sales_des';
        }elseif($coll_sort==4){
            $sort = 'price_des';
        }
        $hasCoupon = $collector['has_coupon']==0?'false':'true';
        $aid  = get_adzoneid($collector['pid']);
        //ios
        $appkey = config('appkey');
        $secretKey = config('secret');
        if(empty($appkey)||empty($secretKey)){
            return json(['msg'=>'密匙不存在！','ok'=>false]);
        }

        $block = trim($collector['block']);
       /* dump($block);
        die;*/

        $c = new \TopClient();
        $c->appkey = $appkey;
        $c->secretKey = $secretKey;
        $req = new \TbkDgMaterialOptionalRequest;
        // $req->setStartDsr("10");
        $req->setPageSize($number);
        $req->setPageNo($page);
        $req->setPlatform("2");//无线端
        $req->setEndTkRate($collector['start_tk_rate']);
        $req->setStartTkRate($collector['end_tk_rate']);
        /*$req->setEndTkRate("1");
        $req->setStartTkRate("1234");*/
       // $req->setEndPrice("10");//折扣上限
      //  $req->setStartPrice("20");//折扣下限
        $req->setIsOverseas("false");
        $req->setIsTmall("false");
        $req->setSort($sort);
        // $req->setItemloc("杭州");
        // $req->setCat("16,18");
        $req->setQ($collector['name'],$block);

        $req->setHasCoupon($hasCoupon);
        // $req->setIp("13.2.33.4");
        $req->setAdzoneId($aid);
        /*$req->setNeedFreeShipment("true");
        $req->setNeedPrepay("true");
        $req->setIncludePayRate30("true");
        $req->setIncludeGoodRate("true");
        $req->setIncludeRfdRate("true");
        $req->setNpxLevel("2");*/
        $resp = $c->execute($req);

        $result =  json_decode(json_encode( $resp),true);
        /* echo "<pre>";
         print_r($result);die;*/

        if(isset($result['code'])){
            return  json(['msg'=>'采集器接口错误:'.$result['sub_msg'],'ok'=>false]);
        }
        $goods  = $result['result_list']['map_data'];
        if(!isset($result['result_list'])){
            return  json(['msg'=>'采集器接口错误!']);
        }
        $list = [];
        foreach($goods as $v){
            if( empty( $v['num_iid'])){
                $list[0] =  $goods;
            }else{
                $list = $goods;
             }
        }
       /* echo "<pre>";
        print_r($list);
        die;*/
        $i = 0;
        $data  = $datas =   [];
        foreach($list as $v){
            $data['gt_id'] = $collector['gt_id'];
            $data['gb_id'] = $collector['gb_id'];
            $data['goods_add_time'] = time();
            $data['goods_id'] = $v['num_iid'];//商品ID
            $data['goods_title'] = $v['title'];//标题
            $data['goods_big_img'] = $v['pict_url'];//大图地址
            $data['goods_small_img'] = isset($v['small_images'])?json_encode($v['small_images']):'';
            $data['goods_detail_url'] = $v['item_url']?$v['item_url']:$v['url'];//商品详情地址
            $data['goods_volume'] = $v['volume'];//月销量
            $data['goods_seller_id'] = $v['seller_id'];//供应商ID，卖方id
            $data['goods_nick'] = isset($v['nick'])?$v['nick']:'';//掌柜旺旺名
            $data['goods_price'] = isset($v['reserve_price'])?$v['reserve_price']:$v['zk_final_price'];//商品价格
            $data['goods_z_price'] = $v['zk_final_price'];//折后价
            $data['goods_shop_title'] = $v['shop_title'];//店铺名称

            $time = intval(time()+72*86400);
            $data['goods_end_time'] = isset($v['coupon_end_time'])?strtotime($v['coupon_end_time']):$time;

            if(!empty($v['coupon_info'])){
                $data['state'] = 1;
                $data['goods_q_price'] = $data['goods_price'] - get_word($v['coupon_info'], '减', '元');//券后价格
                $data['coupon_id']   = isset($v['coupon_id'])?$v['coupon_id']:'';
                $data['coupon_info'] = $v['coupon_info'];
                $data['coupon_end_time'] = isset($v['coupon_end_time'])?$v['coupon_end_time']:0;//优惠券结束时间
                $data['coupon_start_time'] = isset($v['coupon_start_time'])?$v['coupon_start_time']:0;//优惠券开始时间
                $data['coupon_total_count'] = isset($v['coupon_total_count'])?$v['coupon_total_count']:0;//优惠券结总数
                $data['coupon_remain_count'] = isset($v['coupon_remain_count'])?$v['coupon_remain_count']:0;//优惠券剩余量
                $data['coupon_amount'] = get_word($v['coupon_info'], '减', '元');
                $data['coupon_click_url'] = isset($v['coupon_share_url'])?$v['coupon_share_url']:(isset($v['coupon_click_url'])?$v['coupon_click_url']:'');//优惠券链接地址//推广链接
                $data['coupon_total_count'] = $v['coupon_total_count'];//优惠券数量
                $data['coupon_remain_count'] = $v['coupon_remain_count'];//优惠券 剩余量

            }else{
                $data['goods_q_price'] = $v['reserve_price'];
                $data['state'] = 0;
                $data['coupon_id']   = '';
                $data['coupon_info'] = '';
                $data['coupon_end_time'] = 0;//优惠券结束时间
                $data['coupon_start_time'] = 0;//优惠券开始时间
                $data['coupon_total_count'] = 0;//优惠券结总数
                $data['coupon_remain_count'] = 0;//优惠券剩余量
                $data['coupon_amount'] = 0;
                $data['coupon_click_url'] = '';//优惠券链接地址//推广链接
                $data['coupon_total_count'] = 0;//优惠券数量
                $data['coupon_remain_count'] = 0;//优惠券 剩余量
            }

            $data['goods_yj_rate'] = $v['commission_rate'];//佣金比例
            if($data['goods_price']!=0 && $data['goods_z_price']!=0 && $data['goods_q_price']!=0){
                $min = min($data['goods_price'],$data['goods_z_price'],$data['goods_q_price']);
                $data['goods_yongjin'] = round($min* ($v['commission_rate']/10000), 1);//佣金
                $data['member_yongjin'] = $data['goods_yongjin']/2;//会员佣金
            }

            $data['goods_city'] = isset($v['provcity'])?$v['provcity']:'';//商品所在城市
            $data['goods_user_type'] = $v['user_type'];//卖家类型,1表示天猫

            $check_repeat = Db::name('goods')->where('goods_id',$data['goods_id'])->find();//检查重复
            //  print_r($check_repeat);

            if(empty($check_repeat)){
                if($block=='9.9包邮'){
                    if(!empty($data['coupon_info'])){
                        if($data['goods_price']<=9.9||$data['goods_q_price']<=9.9){
                            $datas[] = $data;
                        }
                    }else{
                        if($data['goods_z_price']<=9.9){
                            $datas[] = $data;
                        }
                    }
                }
                else{
                    $datas[] = $data;
                }


            }else{
                Db::startTrans();
                try{
                    if(strpos($block,'9.9')!==false){
                        if(!empty($data['coupon_info'])){
                            if($data['goods_price']<=9.9||$data['goods_q_price']<=9.9){
                                $success = Db::name('goods')->where('goods_id','=',$data['goods_id'])->update($data);
                                Db::name('Collector')->where('id','=',$id)->update($arr);
                            }
                        }else{
                            if($data['goods_z_price']<=9.9){
                                $success = Db::name('goods')->where('goods_id','=',$data['goods_id'])->update($data);
                                Db::name('Collector')->where('id','=',$id)->update($arr);
                            }
                        }

                    }
                    else{
                        $success = Db::name('goods')->where('goods_id','=',$data['goods_id'])->update($data);
                        Db::name('Collector')->where('id','=',$id)->update($arr);
                    }

                    // 提交事务
                    Db::commit();
                    return json(['msg'=>'采集成功！','ok'=>true]);
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return json(['msg'=>$e->getMessage(),'ok'=>false]);
                }

            }
            $i++;
        }

       // 去除goods_id 相同的数组
        $tmp_arr = array();
        foreach($datas as $key=>$value){
            if($block=='9.9包邮'){
                if(!empty($value['coupon_info'])){
                    if($value['goods_price']<=9.9||$value['goods_q_price']<=9.9){
                        $tmp_arr[$key] = $value;
                    }
                }else{
                    if($value['goods_z_price']<=9.9){
                        $tmp_arr[$key] = $value;
                    }
                }

            }
            else{
                $tmp_arr[$key] = $value;
            }
        }
        $res = second_array_unique_bykey($tmp_arr,'goods_id');
        if(!empty($res)){
            Db::startTrans();
            try{

                $success = Db::name('goods')->insertAll($res);
                Db::name('Collector')->where('id','=',$id)->update($arr);

                // 提交事务
                Db::commit();
                $error=$i-$success;
                return json(['msg'=>'采集成功'.$success.'失败'.$error,'ok'=>true]);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(['msg'=>$e->getMessage(),'ok'=>false]);
            }

        }else{
            return json(['msg'=>'此次采集没有符合条件的结果','ok'=>false]);
        }



    }


    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /**
     * 维易 热销高佣产品
     * 采集列表
     */
    public function hot(){
        $type = Db::name('collector_hot')
            ->order('id desc')
            ->paginate(10,false,['query'=>request()->param()]);

        $count = Db::name('collector_hot')->count();
        $this->assign([
            'type'=>$type,
            'count'=>$count,
            'empty'=>'<tr class="text-c empty"><td colspan="4">暂无数据</td></tr>'
        ]);
        return view('');
    }

    /**
     * 热销采集 - 添加页面
     */
    public function hot_add(){
        $id = intval(input('id'));
        if($id){
            $result =Db::name('collector_hot')->where('id',$id)->find();
            $this->assign('result',$result);
        }
        $category = Db::name('goods_type')->where('parent_id',0)->select();
        $block    = Db::name('goods_block')->where('is_tao',2)->select();

        $this->assign([
            'category'=>$category,
            'block'=>$block,
        ]);
        return $this->fetch('collection:hot-add');
    }

    /**
     * 添加保存
     */
    public function hot_hold(){
        $gt_id    = intval(input('classify_id'));
        $block_id = intval(input('block_id'));
        $name     = trim(input('name'));
        $block    = trim(input('block'));
        $page_size = intval(input('page_size'));
        $page_no = intval(input('page_no'));
        if(empty($gt_id)||empty($block_id)||empty($page_size)||empty($page_no)){
            return json(['msg'=>'请填写完整的数据！','ok'=>false]);
        }
        $data = [
            'block'=>$block,
            'name'=>$name,
            'gt_id'=>$gt_id,
            'gb_id'=>$block_id,
            'page_size'=>$page_size,
            'page_no'=>$page_no,
            'add_time'=>time()
        ];

        $res = Db::name('collector_hot')->insert($data);
        //  dump($res);
        if($res){
            return json(['msg'=>'添加成功！','ok'=>true]);
        }else{
            return json(['msg'=>'系统错误，添加失败！','ok'=>false]);
        }


    }
    /**
     * 修改
     */
    public function hot_edit(){
        $id = intval(input('id'));
        $gt_id    = intval(input('classify_id'));
        $block_id = intval(input('block_id'));
        $name     = trim(input('name'));
        $block    = trim(input('block'));
        $page_size = intval(input('page_size'));
        $page_no = intval(input('page_no'));
        if(empty($gt_id)||empty($block_id)||empty($page_size)||empty($page_no)){
            return json(['msg'=>'请填写完整的数据！','ok'=>false]);
        }

        $data = [
            'block'=>$block,
            'name'=>$name,
            'gt_id'=>$gt_id,
            'gb_id'=>$block_id,
            'page_size'=>$page_size,
            'page_no'=>$page_no,
            'add_time'=>time()
        ];

        $res = Db::name('collector_hot')->where('id',$id)->update($data);
        //  dump($res);
        if($res){
            return json(['msg'=>'修改成功！','ok'=>true]);
        }else{
            return json(['msg'=>'系统错误，修改失败！','ok'=>false]);
        }
    }

    /**
     * 热销 采集器删除
     */
    public function hot_del(){
        $id = intval(input('id'));
        $result = Db::name('collector_hot')->where('id',$id)->delete();
        if($result){
            return json(['msg'=>'已删除','ok'=>true]);
        }else{
            return json(['msg'=>'删除失败','ok'=>false]);
        }
    }

    /**
     * 热销采集
     */

    public function hot_collect(){
        $vkey = config('vkey');

        $url = "http://api.vephp.com/products?vekey=" . $vkey;
        $result = file_get_contents($url);
        //dump($result);
        $arr = json_decode($result, true);
        /* echo "<pre>";
         print_r($arr);
         die;*/
        if (isset($arr['error'])) {
            return json(['msg' => $arr['msg'], 'ok' => false]);
        }

        $gb_id = Db::name('icon')->where('name', 'like', '%热销%')->value('id');
        /*dump($gb_id);
        die;*/
        if ($arr['data']) {
            $gb_goods = Db::name('goods')->where('gb_id', $gb_id)->select();
            //  dump($gb_goods);
            if($gb_goods){
                $ids = [];
                foreach($gb_goods as $k=>$v){
                    $ids[] = $v['id'];
                }
                $a = Db::name('goods')->whereIn('id',$ids)->delete();
                //  dump($ids);
            }

            $goods = $arr['data'];
            $datas = $data = [];

            $i = 0;
            foreach ($goods as $k => $v) {
                $data['gb_id'] = $gb_id;
                $data['goods_add_time'] = time();
                $data['goods_id'] = $v['item_id'];//商品ID
                $data['goods_title'] = $v['title'];//标题
                $data['goods_detail_url'] = $v['pict_url'] ? $v['pict_url'] : '';//商品详情地址
                $data['goods_volume'] = $v['volume'];//月销量
                $data['goods_seller_id'] = $v['seller_id'];//供应商ID，卖方id
                $data['goods_description'] = $v['item_description'] ? $v['item_description'] : '';//供应商ID，卖方id
                $data['goods_price'] = $v['zk_final_price'];//商品价格
                $data['goods_z_price'] = $v['zk_final_price'];//折后价

                /* $data['goods_yj_rate'] = $v['commission_rate'];//佣金比例
                 $data['goods_yongjin'] = round($v['zk_final_price'] * ($v['commission_rate'] / 10000), 1);//佣金
                 $data['member_yongjin'] = $data['goods_yongjin'] / 2;//会员佣金*/

                $data['coupon_amount'] = $v['coupon_amount'];
                $data['goods_q_price'] = $data['goods_price'] - $data['coupon_amount'];
                $data['coupon_info'] = '满' . $v['coupon_start_fee'] . '元可用';
                $data['coupon_total_count'] = $v['coupon_total_count'];//优惠券数量
                $data['coupon_end_time'] = isset($v['coupon_end_time']) ? $v['coupon_end_time'] : 0;//优惠券结束时间
                $data['coupon_start_time'] = isset($v['coupon_start_time']) ? $v['coupon_start_time'] : 0;//优惠券开始时间
                $time = intval(time() + 72 * 86400);
                $data['goods_end_time'] = $v['coupon_end_time'] ? $v['coupon_end_time'] : $time;
                $data['goods_user_type'] = $v['user_type'];//卖家类型,1表示天猫

                $data['goods_yj_rate'] = $v['commission_rate'];//佣金比例
                if($data['goods_price']!=0 && $data['goods_z_price']!=0 && $data['goods_q_price']!=0){
                    $min = min($data['goods_price'],$data['goods_z_price'],$data['goods_q_price']);
                    $data['goods_yongjin'] = round($min* ($v['commission_rate']/10000), 1);//佣金
                    $data['member_yongjin'] = $data['goods_yongjin']/2;//会员佣金
                }

                $check_repeat = Db::name('goods')->where('goods_id', $data['goods_id'])->select();//检查重复
                // print_r($check_repeat);die;

                if (empty($check_repeat)) {
                    $datas[] = $data;
                    Db::name('goods')->where('goods_id', $data['goods_id'])->delete();
                } else {
                    $success = Db::name('goods')->where('goods_id', '=', $data['goods_id'])->update($data);
                    if ($success) {
                        return json(['msg' => '采集成功！', 'ok' => true]);
                    } else {
                        return json(['msg' => '采集失败', 'ok' => false]);
                    }

                }
                $i++;



            }

            $res1 = second_array_unique_bykey($datas, 'goods_id');

            if (!empty($res1)) {
                $success = Db::name('goods')->insertAll($res1);
                if ($success) {
                    $error = $i - $success;
                    return json(['msg' => '采集成功' . $success . '失败' . $error, 'ok' => true]);
                } else {
                    return json(['msg' => '采集失败', 'ok' => false]);
                }


            } else {
                return json(['msg' => '此次采集没有符合条件的结果', 'ok' => false]);
            }
        }
    }




}